package pers.vic.xqd.register;

import com.sun.org.apache.regexp.internal.RE;
import org.omg.PortableInterceptor.INACTIVE;
import pers.vic.xqd.framerwork.Url;

import java.io.*;
import java.util.*;

/**
 * 描述:
 * @author Vic.xu
 * @date 2022-02-08 11:23
 */
public class RemoteMapRegister {
    private static Map<String, List<Url>> REGISTER = new HashMap<>();

    public static void register(String interfaceName, Url url){
        List<Url> list = Collections.singletonList(url);
        REGISTER.put(interfaceName, list);
        saveFile();
    }

    /**
     * 模拟负载均衡
     * @return
     */
    public static Url random(String interfaceName){
        REGISTER = getFile();
        List<Url> list = REGISTER.get(interfaceName);
        int n = new Random().nextInt(list.size());
        return list.get(n);
    }

    public static void saveFile(){
        try {
            FileOutputStream fos = new FileOutputStream(new File("/temp.text"));
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(REGISTER);
            fos.close();
            oos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        }
    }

    public static Map<String, List<Url>> getFile(){
        File file;
        try {
            FileInputStream fis = new FileInputStream("/temp.text");
            ObjectInputStream ois = new java.io.ObjectInputStream(fis);
            return (Map<String, List<Url>>) ois.readObject();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }



}
